/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

function dataOnTheFly_onScreenReadySemester(element, params) {
    // Make the proper activity indicator appear
    if (bb.device.isBB10) {
        element.getElementById('bb7Loading').style.display = 'none';
    } else {
        element.getElementById('bb10Loading').style.display = 'none';
    }
    element.getElementById('semNameTemp').innerHTML = params.semName;
}

function dataOnTheFly_initialLoadSemester(element) {
    //display Semester Recap
    var json = JSON.parse(localStorage.getItem('jSemesterRecap'));
    var semRecap = document.getElementById('semesterRecap');
    for(var i=0; i<json.length; i++) { 
        if (json[i].semesterName == element.getElementById('semNameTemp').innerHTML){
            semRecap.innerHTML = "<p style=\"text-align:center\"><b>"+json[i].semesterName+"</b></p><p style=\"text-align:center\"><b>GPA: "+json[i].gpaSemester+"</b></p><p style=\"text-align:center\">You had <u>"+json[i].numberOfCourse+" Course(s)</u> and <u>"+json[i].totalCredit+" Credit(s)</u> in this semester</p>";
        }
    }
        
    //display course in given semester
    var num, out, i, key, value;
    var listPanel = document.getElementById('semesterPanel'),
    curItems = listPanel.getItems();
    var items = [],
    divCourseItem;
    if (window.localStorage) {
        num = window.localStorage.length;
        if (num > 0) {
            for (i = 0; i < num; i = i + 1) {
                if(window.localStorage.key(i) == element.getElementById('semNameTemp').innerHTML){
                    key = window.localStorage.key(i);
                    value = window.localStorage.getItem(key);
                    var jsonSemPanel = JSON.parse(value);
                    for(var j=0; j<jsonSemPanel.length; j++) { 
                        divCourseItem = document.createElement('div');
                        divCourseItem.setAttribute('data-bb-type', 'item');
                        divCourseItem.setAttribute('data-bb-title', jsonSemPanel[j].courseName);
                        divCourseItem.onbtnclick = showConfirm;
                        divCourseItem.innerHTML = "Grade: "+jsonSemPanel[j].grade+" | Credit(s): "+jsonSemPanel[j].credit;
                        items.push(divCourseItem);
                        
                        if (curItems.length > 0) {
                            listPanel.insertItemBefore(divCourseItem, curItems[0]);
                        } else {
                            listPanel.appendItem(divCourseItem);
                        }
                    }
                    break;    
                }
            }
        }
    }
    document.getElementById('ArrowListSemesterRecap').refresh(listPanel);
  
    // re-compute the scrolling area
    if (bb.scroller) {
        bb.scroller.refresh();
    }
    // Remove our waiting and refresh the list
    document.getElementById('waiting').style.display = 'none';
}

function showConfirm(){
    var con = confirm("Are You Sure You Want to Delete This Course?");
    var list = document.getElementById('semesterPanel'),
    selected = list.selected;
    if (con ==true)
    {
        deleteCourse(selected.getTitle());
    }
}

function deleteCourse(courseName){
    semNameDelete = document.getElementById('semNameTemp').innerHTML;
    var json = JSON.parse(localStorage.getItem(semNameDelete));
    credit = 0, grade = 'F';
    for(var i=0; i<json.length; i++) { 
        if(json[i].courseName == courseName) {
            credit = json[i].credit;
            grade = json[i].grade;
            json.splice(i,1);
            localStorage.setItem(semNameDelete, JSON.stringify(json));
            break;
        }
    }
    updateDeleteSemesterRecap(credit, grade, semNameDelete);
    updateDeleteGPARecap();
    alert(courseName+ " Already Deleted.");
    
    //directly delete the display course
    var selected = document.getElementById('semesterPanel').selected,
    item;
    selected.remove();
    
    
}

function updateDeleteSemesterRecap(credit, grade, semNameDelete){
    var json = JSON.parse(localStorage.getItem('jSemesterRecap'));
    for(var i=0; i<json.length; i++) { 
        if(json[i].semesterName == semNameDelete) {
            curGPA = parseFloat(json[i].gpaSemester);
            curTotalCredit = parseInt(json[i].totalCredit);
            credit = parseInt(credit);
            grade = parseFloat(localStorage.getItem(grade));
            updatedCredit = curTotalCredit - credit;
            
            //prevent devide by zero
            if (updatedCredit ==0 ){
                updatedGPA = 0;
            }
            else{
                updatedGPA = ((curGPA * curTotalCredit) - (grade * credit))/ updatedCredit;
            }
            
            json[i].gpaSemester = parseFloat(updatedGPA.toFixed(2));
            json[i].totalCredit = updatedCredit;
            json[i].numberOfCourse--;
            localStorage.setItem('jSemesterRecap', JSON.stringify(json));
            break;
        }
    }
}

//Update for deleted course in jGPARecap
function updateDeleteGPARecap(){
    //recalculate update from jSemesterRecap
    //Iterate jSemesterRecap
    // GPATotal = Sum ( (totalcredit/sumOfTotalCredit)* GPA Semester)
    var json = JSON.parse(localStorage.getItem('jSemesterRecap'));   
    var cumulativeEnumerator = 0;
    var cumulativeCredit = 0;
    var cumulativeCourse =0;
    var semTotal = 0;
    for(var i=0; i<json.length; i++) { 
        if(json[i].numberOfCourse ==0){
            continue;
        }
        else{
            semTotal ++;
            cumulativeEnumerator = parseFloat(cumulativeEnumerator + (json[i].gpaSemester*json[i].totalCredit));
            cumulativeCredit = parseInt(cumulativeCredit + parseInt(json[i].totalCredit));
            cumulativeCourse = parseInt(cumulativeCourse + parseInt(json[i].numberOfCourse));
        }
    }
    var jsonGPA = JSON.parse(localStorage.getItem('jGPARecap'));
    cumulativeGPA = parseFloat((cumulativeEnumerator/cumulativeCredit).toFixed(2));
    //prevent null values
    if(cumulativeGPA == null) {
        jsonGPA[0].gpaTotal = 0;
    }
    else{
        jsonGPA[0].gpaTotal = parseFloat((cumulativeEnumerator/cumulativeCredit).toFixed(2));
    }
    jsonGPA[0].semesterTotal = semTotal;
    jsonGPA[0].creditTotal = cumulativeCredit;
    jsonGPA[0].courseTotal = cumulativeCourse;
    //set new value
    localStorage.setItem('jGPARecap', JSON.stringify(jsonGPA));
}